package leetcode;

/**
 *
 * 有限状态机。好好学
 * @author:xufengxiang
 * @date 2023-02-20 19:44
 */
public class Code8 {


    public static int myAtoi(String s) {
        int length = s.length();
        if(s == null || length ==0){
            return 0;
        }

        int max = 214748364;
        int min = -214748364;

        int result = 0;
        boolean negative = false;
        boolean startNumber = false;
        for(int i=0;i<length;i++){
            char c = s.charAt(i);
            if(c == ' ' && !startNumber){
                continue;
            }

            if(!startNumber){
                if(c == '+'){
                    negative = false;
                    startNumber = true;
                }else if(c == '-'){
                    negative = true;
                    startNumber = true;
                }
                continue;
            }

            //如果当前文本是数字
            if(c >= '0' && c<= '9'){
                int curNum = c - '0';
                if(negative){
                    //负数
                    if(min > result ||  (result == min && curNum > 8)){
                        return -2147483648;
                    }else{
                        result = result * 10 - curNum;
                    }
                }else{
                    //正数
                    if(max < result || (result == max && curNum >7 )){
                        return 2147483647;
                    }else{
                        result = result*10 + curNum;
                    }
                }
            }else if(result !=0){
                //当前文本不是数字
                break;
            }else{
                return 0;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(myAtoi("-91283472332"));
        System.out.println(-2^31);
    }



}
